package xiaolong.zhou.spring_demo.Service.achieve;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import xiaolong.zhou.spring_demo.Mapper.UserMapper;
import xiaolong.zhou.spring_demo.Pojo.SendEmail;
import xiaolong.zhou.spring_demo.Pojo.User;
import xiaolong.zhou.spring_demo.Service.SendEmailImp;
import xiaolong.zhou.spring_demo.Utils.Result;
import xiaolong.zhou.spring_demo.Utils.VerCodeGenerateUtil;

import java.util.concurrent.TimeUnit;

@Service
public class SendEmailCaptchaAchieve implements SendEmailImp {
    @Autowired
    private MailService mailService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送验证码实现类
     * @param sendEmail
     * @return
     */
    @Override
    public Result send(SendEmail sendEmail) {
        if(sendEmail.getEmail() == null){
            return Result.error("参数错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",sendEmail.getEmail());
        Long emailCount = userMapper.selectCount(queryWrapper);
        if(emailCount>0){
            return Result.error("该邮箱已被注册");
        }
        sendEmail.setSub("你本次的验证码是：");
        String verCode = VerCodeGenerateUtil.generateVerCode();
        String content = "您好:\n"
                + "\n本次请求的邮件验证码为:" + verCode + ",本验证码 10 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）";
        sendEmail.setContent(content);
       Boolean send =  mailService.sendTextMail(sendEmail.getEmail(), sendEmail.getSub(), sendEmail.getContent());
       if(send){
           //发送成功将验证码加入session
           redisTemplate.opsForValue().set(sendEmail.getEmail(),verCode.toLowerCase());//不区分大小写
           redisTemplate.expire(sendEmail.getEmail(),600, TimeUnit.SECONDS);
           return Result.success();
       }else {
           return Result.error("邮件发送失败");
       }
    }
}
